app.factory("leafletscript", ['$q', "$window", "LazyService", function ($q, $window, lazy) {
    function LeafletScript() {
        this.map = null;
    }
    LeafletScript.prototype = {
        _load: function () {
            var self = this;
            return lazy.css("http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css").then(function () {
                return lazy.js("http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js").then(function () {
                    return $window.L;
                });
            });
        },
        _init: function (element, lng, lat, zoom) {
            var self = this;
            return self._load().then(function (L) {
                if (!element) throw new Error("element is not defnied.");
                if (!lng) throw new Error("lng is not defnied.");
                if (!lat) throw new Error("lat is not defnied.");
                if (!zoom) throw new Error("zoom is not defnied.");

                self.map = L.map(element).setView([lat, lng], zoom);
                L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
                    attribution: ""
                }).addTo(self.map);
            });
        },
        initShop: function (element, shop) {
            var self = this;

            var lng = shop.location.loc.coordinates[0];
            var lat = shop.location.loc.coordinates[1];

            return self._init(element, lng, lat, 12).then(function () {
                return self.addShop(shop);
            })
        },
        addShop: function (shop) {
            if (!this.map) throw new Error("map is not defined.");
            var self = this;

            var lng = shop.location.loc.coordinates[0];
            var lat = shop.location.loc.coordinates[1];

            $window.L.marker([lat, lng]).addTo(self.map)
                    .bindPopup("<a href=\"#shop/" + shop._id + "\">" + shop.name + "</a>")
                    .openPopup();
        },
        addPosition: function (position) {
            if (!this.map) throw new Error("map is not defined.");
            var self = this;

            var lng = position.lng;
            var lat = position.lat;

            $window.L.marker([lat, lng]).addTo(self.map)
                    .bindPopup(position.type)
                    .openPopup();
        }
    }
    return new LeafletScript();
} ]);
